<template>
  <a-spin :spinning="loading">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{span:4}"
      :wrapper-col="{span:18}"
    >
      <a-form-item label="项目ID" name="id">
        <a-input v-model:value="formState.id" :disabled="type === 1? false: true" />
      </a-form-item>
      <a-form-item label="项目名称" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="项目说明" name="remark">
        <a-textarea v-model:value="formState.remark" :auto-size="{ minRows: 2, maxRows: 6 }"/>
      </a-form-item>
      <a-form-item label="项目图片" :class="type === 1 ? 'img-label' : ''">
        <a-upload
          action="aaa"
          list-type="picture-card"
          v-model:file-list="fileList"
          accept=".jpg,.png"
          class="avatar-uploader"
          :before-upload="beforeUpload"
          @preview="handlePreview">
          <div v-if="type === 3 && fileList.length < 1" class="img-picture">
            <img alt="example" :src="projectRow.imgUrl">
          </div>
          <div v-if="type === 1 && fileList.length < 1">
            <plus-outlined />
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-spin>
  <a-modal
    :visible="previewVisible"
    :footer="null"
    @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script>
import { onMounted, reactive, ref, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'
import { PlusOutlined } from '@ant-design/icons-vue'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  props: {
    loading: {
      type: Boolean,
      required: true
    },
    type: {
      type: Number,
      required: true
    },
    projectRow: {
      type: Object
    }
  },
  emits: ['handle-project'],
  components: {
    PlusOutlined
  },
  setup (props, context) {
    const { proxy } = getCurrentInstance()
    const formRef = ref()
    const store = useStore()
    const formState = reactive({
      id: '',
      name: '',
      remark: ''
    })
    const rules = {
      id: [{ required: true, message: '请输入项目ID', trigger: ['blur', 'change'] }],
      name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }]
      // fileList: [{ required: true, message: '请上传项目图片', trigger: ['blur', 'change'] }]
    }
    // eslint-disable-next-line prefer-const
    let previewVisible = ref(false)
    // eslint-disable-next-line prefer-const
    let previewImage = ref('')
    // eslint-disable-next-line prefer-const
    let fileList = ref([])
    onMounted(() => {
      if (props.type * 1 === 1) {
        rules.id.push({ validator: checkProjectId, trigger: 'blur' })
      }
      if (props.type * 1 === 3) {
        Object.keys(formState).forEach(key => {
          formState[key] = props.projectRow[key]
        })
      }
    })
    const checkProjectId = async (rule, value) => {
      if (store.state.projectIds.indexOf(value) !== -1) {
        return Promise.reject(new Error('存在该项目ID'))
      }
    }
    const handleCancel = () => {
      previewVisible.value = false
    }
    const handleChange = ({ fileList: newFileList }) => {
      fileList.value = newFileList
    }
    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        proxy.$root.$message.error('只能上传jpg或者png图片!')
      }
      return false
    }
    const onSubmit = () => {
      if (props.type * 1 === 1 && fileList.value.length === 0) {
        proxy.$root.$message.error('请上传图片!')
        return
      }
      formRef.value
        .validate()
        .then(async () => {
          const imgFile = fileList.value.length !== 0 ? await getBase64(fileList.value[0].originFileObj) : ''
          context.emit('handle-project', formState, imgFile)
        })
        .catch(error => {
          console.log(error)
        })
    }
    return {
      formRef,
      formState,
      rules,
      previewVisible,
      previewImage,
      fileList,
      handleCancel,
      handleChange,
      handlePreview,
      beforeUpload,
      onSubmit
    }
  }
}
</script>

<style lang='less' scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.img-picture {
  height: 86px;
  width: 86px;
  img {
    width: 100%;
    height: 100%;
  }
}
.img-label {
  /deep/label::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
}
</style>
